package mine.code.question.other;

import org.junit.Test;

public class 字符串转换整数 {
    @Test
    public void run() {
        String str = "42";
        System.out.println(myAtoi(str));
    }

    public int myAtoi(String s) {
        s = s.trim();
        if (s.length() == 0) return 0;
        if (!Character.isDigit(s.charAt(0))
                && s.charAt(0) != '-' && s.charAt(0) != '+')
            return 0;
        int ans = 0;
        boolean neg = s.charAt(0) == '-';
        int i = !Character.isDigit(s.charAt(0)) ? 1 : 0;
        while (i < s.length() && Character.isDigit(s.charAt(i))) {
            int tmp = ((neg ? Integer.MIN_VALUE : Integer.MIN_VALUE + 1) + (s.charAt(i) - '0')) / 10;
            if (tmp > ans) {
                return neg ? Integer.MIN_VALUE : Integer.MAX_VALUE;
            }
            ans = ans * 10 - (s.charAt(i++) - '0');
        }
        return neg ? ans : -ans;
    }
}
